import React, { useEffect, useState } from 'react';
import {
  Form,
  message,
  Modal,
  Input,
  Button,
  Select,
  SelectProps
}
  from 'antd';
import { getTakeAwayGoodRuleAll } from '@/services/takeAwayGoodRuleService';
import { addTakeAwayRuleDetail, getTakeAwayRuleDetailById, updateTakeAwayRuleDetail } from '@/services/takeAwayRuleDetailService';
import DynamicTag from '@/components/DynamicTag';
import { getCookie } from '@/utils/cookieUtils';

interface Props {
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
  id?: number;
}

let ruleOptions: SelectProps['options'] = [];
const UpdateModal: React.FC<Props> = (props) => {
  const [tags, setTags] = useState<string[]>([]);
  const { modalVisible, onSubmit, onCancel, id } = props;
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const getRuleList = async () => {
    const { Items } = await getTakeAwayGoodRuleAll();
    ruleOptions = Items.map((r: any) => {
      return {
        value: r.Id,
        label: r.Name
      }
    })
  }

  const saveRecord = async () => {
    form.validateFields().then(async () => {
      const { StatusCode } = id ? await updateTakeAwayRuleDetail({ ...form.getFieldsValue(), Id: id, Detail: tags?.join(','), ShopId: getCookie("shopId") }, { "@relationships": "DetailValue" }) : await addTakeAwayRuleDetail({ ...form.getFieldsValue(), AddTime: new Date(), Detail: tags?.join(','), ShopId: getCookie("shopId") }, { "@relationships": "DetailValue" });
      if ((id && StatusCode == 0) || (!id && StatusCode == 201)) {
        message.success("保存成功！");
        onSubmit?.();
        form.resetFields();
      }
    }).catch(err => console.log(err));
  }

  const getRuleDetail = async () => {
    if (!id) {
      setIsLoading(true);
      return;
    }

    const { Items } = await getTakeAwayRuleDetailById(id, { "@relationships": "DetailValue" });
    form.setFieldsValue(Items[0]);
    setTags((Items[0].Values ?? []).map((r: any) => {
      return r.Value
    }));
    form.setFieldValue("DefaultValue", (Items[0].Values ?? []).find((r: any) => r.IsDefault)?.Value);
    setIsLoading(true);
  }

  useEffect(() => {
    setIsLoading(false);
    form.resetFields();
    getRuleList();
    getRuleDetail();
  }, [id])


  return (
    <Modal
      width={700}
      destroyOnClose
      title="新建"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={[
        <Button key="submit" onClick={() => { saveRecord() }} type="primary">
          保存
        </Button>,
        <Button key="back" onClick={() => onCancel()} >
          取消
        </Button>,
      ]}
    >
      {id && tags.length > 0 ? <Form
        onFinish={saveRecord}
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: 600 }}
        form={form}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item label='规格名称' name='RuleId'  >
          {(ruleOptions || []).length > 0 ? <Select placeholder='请选择规格名称' options={ruleOptions} /> :
            <Select placeholder='请选择规格名称' />}
        </Form.Item>
        <Form.Item label='规格详情' name='Name'>
          <Input />
        </Form.Item>
        <Form.Item label='规格值' name='Detail'  >
          {isLoading ? <DynamicTag callBack={setTags} initialTags={tags} tagText={'属性名称'} /> : null}
        </Form.Item>
        <Form.Item label='默认值' name='DefaultValue'  >
          <Select options={tags.map(r => {
            return {
              value: r,
              label: r
            }
          })} />
        </Form.Item>
      </Form> : <Form
        onFinish={saveRecord}
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: 600 }}
        form={form}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item label='规格名称' name='RuleId' rules={[{ required: true }]} >
          {(ruleOptions || []).length > 0 ? <Select placeholder='请选择规格名称' options={ruleOptions} /> :
            <Select placeholder='请选择规格名称' />}
        </Form.Item>
        <Form.Item label='规格详情' name='Value' rules={[{ required: true }]}  ><Input /></Form.Item>
        <Form.Item label='规格值' name='Detail' rules={[{ required: true }]} >
          <DynamicTag callBack={(values) => { setTags(values); form.setFieldValue("Detail", values); }} initialTags={[]} tagText={'属性名称'} />
        </Form.Item>
        <Form.Item label='默认值' name='DefaultValue' rules={[{ required: true }]} >
          <Select options={tags.map(r => {
            return {
              value: r,
              label: r
            }
          })} />
        </Form.Item>
      </Form>}
    </Modal>
  );
}

export default UpdateModal;
